<!--
 @description 异常验收申请
 @fileName Edit.vue
 @author zengqiongying
 @created 2023/06/18 14:52:38
-->
<template>
  <div class="has-foot-pb">
    <Cell title="申请序号" custom is-column required :right="false" cellClassName="grey-bg">
      <qmp-field v-model="formData.abnormalNo" maxlength="50" placeholder="请输入申请序号" class="no-field" clearable />
    </Cell>
    <div class="pd-lr-main">
      <FileItem
        v-for="(item, i) in list"
        :key="`${i}-${item.afid}`"
        :sortNumberList="sortNumberList"
        v-model="list[i]"
        :caid="caid"
        @delete="onDelete(i)"
      />
    </div>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main-outline" @click="onCreate">新增照片</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, nextTick, getCurrentInstance, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { IAnyKeyObject } from '@/types/common'
  import { saveAbnormal, queryAbnormaDetail } from '@/apis/Abnormal'
  import { AbnormalFileDelete } from '@/mixins/TaskCommon'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import Cell from '@/components/Cell/index.vue'
  import FileItem from '@/views/components/Abnormal/FileItem.vue'
  import { initFormData } from '@/utils'
  export default {
    name: 'AbnormalEdit',
    components: { Cell, FileItem },
    setup() {
      const { proxy }: any = getCurrentInstance()
      const $route = useRoute()
      const $router = useRouter()
      const datas = reactive<IAnyKeyObject>({
        caid: $route.query?.caid || '', // 验收ID
        said: $route.query?.said || '', // 异常ID
        detail: {
          acceptID: '',
          said: '',
          abnormalNo: ''
        },
        formData: {
          acceptID: '',
          abnormalNo: ''
        },
        list: [],
        keyboard: {
          show: false
        }
      })
      datas.keyboard = GetKeyboardMixin()

      const sortNumberList = computed(() => {
        if (datas.list.length === 0) {
          return []
        }
        const list = datas.list.filter((v: any) => ![null, undefined, ''].includes(v.sortNumber))
        return list.map((v: any) => v.sortNumber)
      })

      const fileItem: IAnyKeyObject = {
        //异常图片信息字段
        acceptID: '',
        afid: '',
        sortNumber: '', // 序号
        sysFileUrl: '', // 图片地址
        imgOriginName: '', //图片原始名称
        imgCustomName: '' //图片名称
      }
      const onCreate = () => {
        const obj: any = {
          ...fileItem
        }
        datas.list.push(obj)
      }

      const onDelete = (i: number) => {
        const afid = datas.list[i].afid || ''
        if (!afid) {
          datas.list.splice(i, 1)
          return
        }

        AbnormalFileDelete(afid, () => {
          datas.list.splice(i, 1)
        })
      }
      const onSave = () => {
        if ([null, undefined, ''].includes(datas.formData.abnormalNo)) {
          proxy.$toast('请输申请序号')
          return
        }
        if (datas.list.length === 0) {
          proxy.$toast('请至少新增一个图片文件')
          return
        }
        const verifySorts: any = []
        let flag = true // 序号是否有效
        let emptysort = false // 序号是否为空
        let imgFiles = [] // 图片
        const acceptID = datas.caid
        const abnormalFiles = datas.list.map((v: any) => {
          if ([null, undefined, ''].includes(v.sortNumber)) {
            emptysort = true
          } else {
            const i = verifySorts.find((num: any) => Number(num) === Number(v.sortNumber))
            if (i > -1) {
              flag = false
            } else {
              verifySorts.push(v.sortNumber)
            }
          }
          if (v.sysFileUrl) {
            imgFiles.push(v.sysFileUrl)
          }
          return {
            ...v,
            imgCustomName: v.imgOriginName,
            acceptID
          }
        })
        if (emptysort) {
          proxy.$toast('图片序号不能为空')
          return
        }
        if (!flag) {
          proxy.$toast('图片序号存在重复序号')
          return
        }
        if (imgFiles.length < abnormalFiles.length) {
          proxy.$toast('有异常图片为空，不能保存，请检查')
          return
        }
        const params = {
          said: datas.said,
          abnormalNo: datas.formData.abnormalNo,
          acceptID,
          abnormalFiles
        }
        saveAbnormal(params).then((res) => {
          proxy.$toast('保存成功')
          proxy.$SimpleEvents.emit('refreshTaskDetail', datas.caid)
          $router.goBack()
        })
      }
      const getDetailData = () => {
        queryAbnormaDetail(datas.said).then((res) => {
          datas.detail = res.data || {}
          initFormData(datas.detail, datas.formData)
          datas.list = res.data.abnormalFiles || []
          if (datas.list.length === 0) {
            onCreate()
          }
        })
      }
      if (datas.said) {
        getDetailData()
      } else {
        onCreate()
      }

      return {
        ...toRefs(datas),
        sortNumberList,
        onCreate,
        onDelete,
        onSave
      }
    }
  }
</script>
<style lang="less" scoped>
  .grey-bg {
    background: var(--bg-global-weak);
  }
  .no-field {
    background: var(--input-bg-default);
    border-radius: var(--radius-xl);
    border: 1px solid var(--input-line-active);
  }
  .pd-tb-8 {
    padding: 8px 0;
  }
  .btn-create {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    font: var(--font-main-body);
    color: var(--texticon-color-brand-normal);
    background: var(--bg-global-weaker);
    border-radius: var(--radius-xl);
  }
</style>
